package offer.offer02;

/**
 *
 */
public class Solution29_2 {
    int p = 0;

    public int[] spiralOrder(int[][] matrix) {
        if (matrix == null || matrix.length == 0) {
            return new int[0];
        }

        int r = matrix.length;
        int c = matrix[0].length;
        int[] result = new int[r * c];
        for (int i = 0; i * 2 < r && i * 2 < c; i++) {
            printRect(matrix, i, result);
        }

        return result;
    }

    private void printRect(int[][] matrix, int i, int[] result) {
        int r = matrix.length;
        int c = matrix[0].length;

        int left = i; int top = i;
        int right = c - i - 1; int bottom = r - i - 1;
        for (int k = left; k <= right; k++) {
            result[p++] = matrix[top][k];
        }
        for (int k = top + 1; k <= bottom; k++) {
            result[p++] = matrix[k][right];
        }
        if (left < right && top < bottom) {
            for (int k = right - 1; k >= left; k--) {
                result[p++] = matrix[bottom][k];
            }
            for (int k = bottom - 1; k >= top + 1; k--) {
                result[p++] = matrix[k][left];
            }
        }
    }
}
